<?php

/**
 * @Author: king
 * @Date:   2019-05-05 20:14:51
 * @Last Modified by:   king
 * @Last Modified time: 2019-06-04 23:48:14
 */
namespace App\Http\Controllers\Api\v3;

use App\Http\Controllers\Api\BaseController;
use App\Models\Api\User;
use App\Models\Api\Orders;
use App\Models\Api\LanmeiUserAccount;
use App\Exceptions\ApiException;
use Illuminate\Http\Request;
use DB;

class DelAccountController extends BaseController
{
    protected $nodel;
    public function __construct()
    {
        parent::__construct();
        $this->nodel = config('code.nodel');
    }
    /**
     * @return Json
     * @throws ApiException
     */
    public function getAccountInfo(Request $request)
    {
        $uid = $request->uid;
        $code    = $request->input('code');
        $tel    = $request->input('tel');
        $time = time();
        // 获取账户信息
        $OrdersModel = new Orders();
        $User = new User();
        if (!$tel || !$code || strlen($code) != 6) {
            return show(config('code.error'), '验证码错误');
        }
        if (!preg_match("/^1[3456789]{1}\d{9}$/", $tel)) {
            return show(config('code.error'), '手机号无效');
        }
        $orders = $OrdersModel->getUnOrder(['uid' => $uid, 'type' => '1', 'is_del' => $this->nodel, 'page' => '1']);
        $account  = $User->where(['status'=>'0','forbidden'=>'1','id'=>$uid])->first();
        $accountInfo = (new LanmeiUserAccount())->getAccountInfoAndCreate($uid);
       if(!empty($orders)){

         return show(config('code.error'), '你的账户有未满半年的订单不能注销,请联系客服');
       }
       if(!empty($account['id'])){

           return show(config('code.error'), '你的账户有异常不能注销,请联系客服');
       }
       if($accountInfo['balance']>=1){

           return show(config('code.error'), '你的账户有未消费金额不能注销,请联系客服');
       }
        // 若未注册
         if (!empty($code)){
            try{
                // 判断code是否正确
                $data = DB::table('tel_login')->where(['tel'=>$tel,'code'=>$code])->first();
            }catch (\Exception $e)
            {
                return show(config('code.error'),'查询验证码失败');
            }
            // code输入错误
            if(empty($data))
            {
                return show(config('code.error'), '验证码错误');
            }
            else
            {
//                // 判断code是否过期
                if ($data->expire_time < $time)
                {
                    return show(config('code.error'), '验证码已过期');
                }

                try{
                    $result = (new User())->where(['id'=>$uid])->update(['status' => '0']);
                }catch (\Exception $e)
                {
                    $result = false;
                }
                // 开始绑定手机号
                if ($result)
                {
                    return show(config('code.success'), '注销成功');
                }else{
                    return show(config('code.error'), '注销失败');
                }
            }
        }

    }

}
